import cv2
import os
import shutil
import time
import datetime
from urllib3 import encode_multipart_formdata
import requests


# test
# gst-launch-1.0 nvarguscamerasrc num-buffers=1 ! 'video/x-raw(memory:NVMM), width=1920, height=1080, format=NV12' ! nvjpegenc ! filesink location=test.jpg

def post_files(url,header,data,filename,filepath):
    """
        :param files: (optional) Dictionary of ``'name': file-like-objects`` (or ``{'name': file-tuple}``) for multipart encoding upload.
        ``file-tuple`` can be a 2-tuple ``('filename', fileobj)``, 3-tuple ``('filename', fileobj, 'content_type')``
        or a 4-tuple ``('filename', fileobj, 'content_type', custom_headers)``, where ``'content-type'`` is a string
        defining the content type of the given file and ``custom_headers`` a dict-like object containing additional headers
        to add for the file.
    """
    data['file']= (filename, open(filepath,'rb').read())
    encode_data = encode_multipart_formdata(data)
    data = encode_data[0]
    header['Content-Type'] = encode_data[1]
    r = requests.post(url, headers=header, data=data)
    return (r.content)

url = 'http://47.101.174.200:8006/upload'
header = {}
data = {}

if __name__=="__main__":
    newfile="test.jpg"
    cmd = "gst-launch-1.0 nvarguscamerasrc num-buffers=1 ! 'video/x-raw(memory:NVMM), width=1920, height=1080, format=NV12' ! nvjpegenc ! filesink location=%s"%(newfile)
    while True:
        filename = time.strftime("%Y_%m_%d_%H_%M_%S.jpg", time.localtime())
        os.system(cmd)
        shutil.copyfile(newfile, filename)
        i = datetime.datetime.now()
        hour = i.hour
        filepath = filename  
        try:
            post_files(url,header,data,filename,filepath)
        except:
            print("Post failed: " + url + ",filename: "+filename)
        sleeptime = 600
        if hour > 22 or hour < 5:
            sleeptime = 3000
        os.remove(filename)
        time.sleep(sleeptime)
